<!doctype html>



  


<html class="theme-next pisces use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.8.0">
  <meta name="baidu-site-verification" content="bk1wz1wzS4">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">



<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">












  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=5.1.0" rel="stylesheet" type="text/css">


  <meta name="keywords" content="学习,">








  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.1.0">






<meta name="description" content="命名规范类文件都是以.class.php为后缀（这里是指的ThinkPHP内部使用的类库文件，不代表外部加载的类库文件），使用驼峰法命名，并且首字母大写，例如 DbMysql.class.php；类的命名空间地址和所在的路径地址一致，例如 Home\Controller\UserController类所在的路径应该是 Application/Home/Controller/UserControll">
<meta name="keywords" content="学习">
<meta property="og:type" content="article">
<meta property="og:title" content="ThinkPHP开发规范">
<meta property="og:url" content="https://youandme66.github.io/2017/07/26/first/index.html">
<meta property="og:site_name" content="腊月的季节">
<meta property="og:description" content="命名规范类文件都是以.class.php为后缀（这里是指的ThinkPHP内部使用的类库文件，不代表外部加载的类库文件），使用驼峰法命名，并且首字母大写，例如 DbMysql.class.php；类的命名空间地址和所在的路径地址一致，例如 Home\Controller\UserController类所在的路径应该是 Application/Home/Controller/UserControll">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2017-07-26T03:44:46.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="ThinkPHP开发规范">
<meta name="twitter:description" content="命名规范类文件都是以.class.php为后缀（这里是指的ThinkPHP内部使用的类库文件，不代表外部加载的类库文件），使用驼峰法命名，并且首字母大写，例如 DbMysql.class.php；类的命名空间地址和所在的路径地址一致，例如 Home\Controller\UserController类所在的路径应该是 Application/Home/Controller/UserControll">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Pisces',
    sidebar: {"position":"left","display":"post"},
    fancybox: true,
    motion: true,
    duoshuo: {
      userId: '0',
      author: 'youandme'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://youandme66.github.io/2017/07/26/first/">





  <title> ThinkPHP开发规范 | 腊月的季节 </title>
  <script>
  (function(){
    var bp = document.createElement('script');
    var curProtocol = window.location.protocol.split(':')[0];
    if (curProtocol === 'https') {
        bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
    }
    else {
        bp.src = 'http://push.zhanzhang.baidu.com/push.js';
    }
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(bp, s);
  })();
</script>
</head>

<body itemscope="" itemtype="http://schema.org/WebPage" lang="zh-Hans">

  










  
  
    
  

  <div class="container one-collumn sidebar-position-left page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope="" itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-meta ">
  

  <div class="custom-logo-site-title">
    <a href="/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <span class="site-title">腊月的季节</span>
      <span class="logo-line-after"><i></i></span>
    </a>
  </div>
  <p class="site-subtitle"></p>
</div>

<div class="site-nav-toggle">
  <button>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
  </button>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br>
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>
            
            标签
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup">
 <span class="search-icon fa fa-search"></span>
 <input type="text" id="local-search-input">
 <div id="local-search-result"></div>
 <span class="popup-btn-close">close</span>
</div>


    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal " itemscope="" itemtype="http://schema.org/Article">
  <link itemprop="mainEntityOfPage" href="https://youandme66.github.io/2017/07/26/first/">

  <span style="display:none" itemprop="author" itemscope="" itemtype="http://schema.org/Person">
    <meta itemprop="name" content="腊月的季节">
    <meta itemprop="description" content="">
    <meta itemprop="image" content="/uploads/avatar.jpg">
  </span>

  <span style="display:none" itemprop="publisher" itemscope="" itemtype="http://schema.org/Organization">
    <meta itemprop="name" content="腊月的季节">
    <span style="display:none" itemprop="logo" itemscope="" itemtype="http://schema.org/ImageObject">
      <img style="display:none;" itemprop="url image" alt="腊月的季节" src="">
    </span>
  </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
            
            
              
                ThinkPHP开发规范
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>
              <time title="Post created" itemprop="dateCreated datePublished" datetime="2017-07-26T00:00:00+08:00">
                2017-07-26
              </time>
            

            

            
          </span>

          
            <span class="post-category">
              <span class="post-meta-divider">|</span>
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
              
                <span itemprop="about" itemscope="" itemtype="http://schema.org/Thing">
                  <a href="/categories/PHP/" itemprop="url" rel="index">
                    <span itemprop="name">PHP</span>
                  </a>
                </span>

                
                
                  ， 
                
              
                <span itemprop="about" itemscope="" itemtype="http://schema.org/Thing">
                  <a href="/categories/PHP/ThinkPHP/" itemprop="url" rel="index">
                    <span itemprop="name">ThinkPHP</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
            <!--noindex-->
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <span class="post-meta-item-icon">
                  <i class="fa fa-comment-o"></i>
                  <a href="/2017/07/26/first/#comments" itemprop="discussionUrl">
                    <span class="post-comments-count hc-comment-count" data-xid="2017/07/26/first/" itemprop="commentsCount"></span>
                  </a>
                </span>
              </span>
              <!--/noindex-->
            
          

          

          
          
             <span id="/2017/07/26/first/" class="leancloud_visitors" data-flag-title="ThinkPHP开发规范">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               <span class="post-meta-item-text">阅读次数 </span>
               <span class="leancloud-visitors-count"></span>
              </span>
          

          

          

        </div>
      </header>
    


    <div class="post-body" itemprop="articleBody">

      
      

      
        <h3 id="命名规范"><a href="#命名规范" class="headerlink" title="命名规范"></a>命名规范</h3><p>类文件都是以.class.php为后缀（这里是指的ThinkPHP内部使用的类库文件，不代表外部加载的类库文件），使用驼峰法命名，并且首字母大写，例如 DbMysql.class.php；<br>类的命名空间地址和所在的路径地址一致，例如 Home\Controller\UserController类所在的路径应该是 Application/Home/Controller/UserController.class.php；<br>确保文件的命名和调用大小写一致，是由于在类Unix系统上面，对大小写是敏感的（而ThinkPHP在调试模式下面，即使在Windows平台也会严格检查大小写）；<br>类名和文件名一致（包括上面说的大小写一致），例如 UserController类的文件命名是UserController.class.php， InfoModel类的文件名是InfoModel.class.php， 并且不同的类库的类命名有一定的规范；<br>函数、配置文件等其他类库文件之外的一般是以.php为后缀（第三方引入的不做要求）；<br>函数的命名使用小写字母和下划线的方式，例如 get_client_ip；<br>方法的命名使用驼峰法，并且首字母小写或者使用下划线“_”，例如 getUserName，<em>parseType，通常下划线开头的方法属于私有方法；<br>属性的命名使用驼峰法，并且首字母小写或者使用下划线“</em>”，例如 tableName、_instance，通常下划线开头的属性属于私有属性；<br>以双下划线“<strong>”打头的函数或方法作为魔法方法，例如 </strong>call 和 __autoload；<br>常量以大写字母和下划线命名，例如 HAS_ONE和 MANY_TO_MANY；<br>配置参数以大写字母和下划线命名，例如HTML_CACHE_ON；<br>语言变量以大写字母和下划线命名，例如MY_LANG，以下划线打头的语言变量通常用于系统语言变量，例如 _CLASS_NOT_EXIST_；<br>对变量的命名没有强制的规范，可以根据团队规范来进行；<br>ThinkPHP的模板文件默认是以.html 为后缀（可以通过配置修改）；<br>数据表和字段采用小写加下划线方式命名，并注意字段名不要以下划线开头，例如 think_user 表和 user_name字段是正确写法，类似 _username 这样的数据表字段可能会被过滤。</p>
<h3 id="配置"><a href="#配置" class="headerlink" title="配置"></a>配置</h3><p>ThinkPHP框架中所有配置文件的定义格式均采用返回PHP数组的方式，格式为：<br><figure class="highlight php"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//项目配置文件</span></span><br><span class="line"><span class="keyword">return</span> <span class="keyword">array</span>(</span><br><span class="line">    <span class="string">'DEFAULT_MODULE'</span>     =&gt; <span class="string">'Index'</span>, <span class="comment">//默认模块</span></span><br><span class="line">    <span class="string">'URL_MODEL'</span>          =&gt; <span class="string">'2'</span>, <span class="comment">//URL模式</span></span><br><span class="line">    <span class="string">'SESSION_AUTO_START'</span> =&gt; <span class="keyword">true</span>, <span class="comment">//是否开启session</span></span><br><span class="line">    <span class="comment">//更多配置参数</span></span><br><span class="line">    <span class="comment">//...</span></span><br><span class="line">);</span><br></pre></td></tr></table></figure></p>
<p>配置参数不区分大小写（因为无论大小写定义都会转换成小写），所以下面的配置等效：<br><figure class="highlight php"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//项目配置文件</span></span><br><span class="line"><span class="keyword">return</span> <span class="keyword">array</span>(</span><br><span class="line">    <span class="string">'default_module'</span>     =&gt; <span class="string">'Index'</span>, <span class="comment">//默认模块</span></span><br><span class="line">    <span class="string">'url_model'</span>          =&gt; <span class="string">'2'</span>, <span class="comment">//URL模式</span></span><br><span class="line">    <span class="string">'session_auto_start'</span> =&gt; <span class="keyword">true</span>, <span class="comment">//是否开启session</span></span><br><span class="line">    <span class="comment">//更多配置参数</span></span><br><span class="line">    <span class="comment">//...</span></span><br><span class="line">);</span><br></pre></td></tr></table></figure></p>
<figure class="highlight php"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//项目配置文件</span></span><br><span class="line"><span class="keyword">return</span> <span class="keyword">array</span>(</span><br><span class="line">    <span class="string">'DEFAULT_MODULE'</span>     =&gt; <span class="string">'Index'</span>, <span class="comment">//默认模块</span></span><br><span class="line">    <span class="string">'URL_MODEL'</span>          =&gt; <span class="string">'2'</span>, <span class="comment">//URL模式</span></span><br><span class="line">    <span class="string">'SESSION_AUTO_START'</span> =&gt; <span class="keyword">true</span>, <span class="comment">//是否开启session</span></span><br><span class="line">    <span class="string">'USER_CONFIG'</span>        =&gt; <span class="keyword">array</span>(</span><br><span class="line">        <span class="string">'USER_AUTH'</span> =&gt; <span class="keyword">true</span>,</span><br><span class="line">        <span class="string">'USER_TYPE'</span> =&gt; <span class="number">2</span>,</span><br><span class="line">    ),</span><br><span class="line">    <span class="comment">//更多配置参数</span></span><br><span class="line">    <span class="comment">//...</span></span><br><span class="line">);</span><br></pre></td></tr></table></figure>
<p>我们可以在应用入口文件中定义应用的配置文件的后缀，例如：<br><figure class="highlight php"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">define(<span class="string">'CONF_EXT'</span>,<span class="string">'.ini'</span>);</span><br></pre></td></tr></table></figure></p>
<p>配置文件加载顺序<br>惯例配置-&gt;应用配置-&gt;模式配置-&gt;调试配置-&gt;状态配置-&gt;模块配置-&gt;扩展配置-&gt;动态配置<br>惯例配置;<br>惯例重于配置是系统遵循的一个重要思想，框架内置有一个惯例配置文件（位于ThinkPHP/Conf/convention.php），按照大多数的使用对常用参数进行了默认配置。所以，对于应用的配置文件，往往只需要配置和惯例配置不同的或者新增的配置参数，如果你完全采用默认配置，甚至可以不需要定义任何配置文件。<br>应用配置:<br>应用配置文件也就是调用所有模块之前都会首先加载的公共配置文件（默认位于Application/Common/Conf/config.php）。<br>模式配置:<br>如果使用了普通应用模式之外的应用模式的话，还可以为应用模式（后面会有描述）单独定义配置文件，文件命名规范是： Application/Common/Conf/config_应用模式名称.php（仅在运行该模式下面才会加载）。<br>调试配置:<br>如果开启调试模式的话，则会自动加载框架的调试配置文件（位于ThinkPHP/Conf/debug.php）和应用调试配置文件（位于Application/Common/Conf/debug.php）<br>状态配置:<br>每个应用都可以在不同的情况下设置自己的状态（或者称之为应用场景），并且加载不同的配置文件。<br>举个例子，你需要在公司和家里分别设置不同的数据库测试环境。那么可以这样处理，在公司环境中，我们在入口文件中定义：<br><figure class="highlight php"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">define(<span class="string">'APP_STATUS'</span>,<span class="string">'office'</span>);</span><br></pre></td></tr></table></figure></p>
<p>那么就会自动加载该状态对应的配置文件（位于Application/Common/Conf/office.php）。<br>如果我们回家后，我们修改定义为：<br><figure class="highlight php"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">define(<span class="string">'APP_STATUS'</span>,<span class="string">'home'</span>);</span><br></pre></td></tr></table></figure></p>
<p>那么就会自动加载该状态对应的配置文件（位于Application/Common/Conf/home.php）。<br>模块配置:<br>每个模块会自动加载自己的配置文件（位于Application/当前模块名/Conf/config.php）。<br>如果使用了普通模式之外的其他应用模式，你还可以为应用模式单独定义配置文件，命名规范为： Application/当前模块名/Conf/config_应用模式名称.php（仅在运行该模式下面才会加载）。</p>
<p>读取配置<br><figure class="highlight php"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">$model = C(<span class="string">'URL_MODEL'</span>);</span><br></pre></td></tr></table></figure></p>
<p>如果url_model尚未存在设置，则返回NULL。<br>因为配置参数是全局有效的，因此C方法可以在任何地方读取任何配置，即使某个设置参数已经生效过期了。</p>
<p>动态配置<br>C(‘参数名称’,’新的参数值’);<br>动态配置赋值仅对当前请求有效，不会对以后的请求造成影响。<br>动态改变配置参数的方法和读取配置的方法在使用上面非常接近，都是使用C方法，只是参数的不同。 也可以支持二维数组的读取和设置，使用点语法进行操作，如下：<br><figure class="highlight php"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 获取已经设置的参数值</span></span><br><span class="line">C(<span class="string">'USER_CONFIG.USER_TYPE'</span>);</span><br><span class="line"><span class="comment">//设置新的值</span></span><br><span class="line">C(<span class="string">'USER_CONFIG.USER_TYPE'</span>,<span class="number">1</span>);</span><br></pre></td></tr></table></figure></p>
<p>扩展配置<br>扩展配置可以支持自动加载额外的自定义配置文件，并且配置格式和项目配置一样。 设置扩展配置的方式如下（多个文件用逗号分隔）：<br><figure class="highlight php"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 加载扩展配置文件</span></span><br><span class="line"><span class="string">'LOAD_EXT_CONFIG'</span> =&gt; <span class="string">'user,db'</span>,</span><br></pre></td></tr></table></figure></p>
<p>假设扩展配置文件user.php 和db.php分别用于用户配置和数据库配置，这样做的好处是哪怕以后关闭调试模式，你修改db配置文件后依然会自动生效。<br>如果在应用公共设置文件中配置的话，那么会自动加载应用公共配置目录下面的配置文件Application/Common/Conf/user.php和Application/Common/Conf/db.php。<br>如果在模块（假设是Home模块）的配置文件中配置的话，则会自动加载模块目录下面的配置文件 Application/Home/Conf/user.php 和 Application/Home/Conf/db.php。<br>默认情况下，扩展配置文件中的设置参数会并入项目配置文件中。也就是默认都是一级配置参数，例如user.php中的配置参数如下：<br><figure class="highlight php"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&lt;?php</span></span><br><span class="line"><span class="comment">//用户配置文件</span></span><br><span class="line"><span class="keyword">return</span> <span class="keyword">array</span>(</span><br><span class="line">    <span class="string">'USER_TYPE'</span>      =&gt; <span class="number">2</span>, <span class="comment">//用户类型</span></span><br><span class="line">    <span class="string">'USER_AUTH_ID'</span>   =&gt; <span class="number">10</span>, <span class="comment">//用户认证ID</span></span><br><span class="line">    <span class="string">'USER_AUTH_TYPE'</span> =&gt; <span class="number">2</span>, <span class="comment">//用户认证模式</span></span><br><span class="line">);</span><br></pre></td></tr></table></figure></p>
<p>那么，最终获取用户参数的方式是：<br><figure class="highlight php"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">C(<span class="string">'USER_AUTH_ID'</span>);</span><br></pre></td></tr></table></figure></p>
<p>如果配置文件改成：<br><figure class="highlight php"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 加载扩展配置文件</span></span><br><span class="line"><span class="string">'LOAD_EXT_CONFIG'</span> =&gt; <span class="keyword">array</span>(<span class="string">'USER'</span>=&gt;<span class="string">'user'</span>,<span class="string">'DB'</span>=&gt;<span class="string">'db'</span>),</span><br></pre></td></tr></table></figure></p>
<p>则最终获取用户参数的方式改成：<br><figure class="highlight php"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">C(<span class="string">'USER.USER_AUTH_ID'</span>);</span><br></pre></td></tr></table></figure></p>
<p>批量配置<br>C配置方法支持批量配置，例如：<br><figure class="highlight php"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">$config = <span class="keyword">array</span>(<span class="string">'WEB_SITE_TITLE'</span>=&gt;<span class="string">'ThinkPHP'</span>,<span class="string">'WEB_SITE_DESCRIPTION'</span>=&gt;<span class="string">'开源PHP框架'</span>);</span><br><span class="line">C($config);</span><br></pre></td></tr></table></figure></p>
<p>$config数组中的配置参数会合并到现有的全局配置中。<br>我们可以通过这种方式读取数据库中的配置参数，例如：<br><figure class="highlight php"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 读取数据库中的配置（假设有一个config表用于保存配置参数）</span></span><br><span class="line">$config =   M(<span class="string">'Config'</span>)-&gt;getField(<span class="string">'name,value'</span>);</span><br><span class="line"><span class="comment">// config是一个关联数组 键值就是配置参数 值就是配置值</span></span><br><span class="line"><span class="comment">// 例如： array('config1'=&gt;'val1','config2'=&gt;'val2',...)</span></span><br><span class="line">C($config); <span class="comment">// 合并配置参数到全局配置</span></span><br></pre></td></tr></table></figure></p>
<p>合并之后，我们就可以和前面读取普通配置参数一样，读取数据库中的配置参数了，当然也可以动态改变。<br><figure class="highlight php"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 读取合并到全局配置中的数据库中的配置参数</span></span><br><span class="line">C(<span class="string">'CONFIG1'</span>);</span><br><span class="line"><span class="comment">// 动态改变配置参数（当前请求有效，不会自动保存到数据库）</span></span><br><span class="line">C(<span class="string">'CONFIG2'</span>,<span class="string">'VALUE_NEW'</span>);</span><br></pre></td></tr></table></figure></p>
<h3 id="架构"><a href="#架构" class="headerlink" title="架构"></a>架构</h3><p>模块化设计<br>一个完整的ThinkPHP应用基于模块/控制器/操作设计，并且，如果有需要的话，可以支持多入口文件和多级控制器。<br>一个典型的URL访问规则是:<br><figure class="highlight php"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">http:<span class="comment">//serverName/index.php（或者其他应用入口文件）/模块/控制器/操作/[参数名/参数值...]</span></span><br></pre></td></tr></table></figure></p>
<p>解释下其中的几个概念:<br>|名称|描述|<br>|-|-|<br>|应用|基于同一个入口文件访问的项目我们称之为一个应用。|<br>|模块|一个应用下面可以包含多个模块，每个模块在应用目录下面都是一个独立的子目录。|<br>|控制器|每个模块可以包含多个控制器，一个控制器通常体现为一个控制器类。|<br>|操作|每个控制器类可以包含多个操作方法，也可能是绑定的某个操作类，每个操作是URL访问的最小单元。|<br>模块化设计的思想下面模块是最重要的部分，模块其实是一个包含配置文件、函数文件和MVC文件（目录）的集合。<br>新版采用模块化的设计架构，下面是一个应用目录下面的模块目录结构，每个模块可以方便的卸载和部署，并且支持公共模块。<br><figure class="highlight sh"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">Application      默认应用目录（可以设置）</span><br><span class="line">├─Common         公共模块（不能直接访问）</span><br><span class="line">├─Home           前台模块</span><br><span class="line">├─Admin          后台模块</span><br><span class="line">├─...            其他更多模块</span><br><span class="line">├─Runtime        默认运行时目录（可以设置）</span><br></pre></td></tr></table></figure></p>
<p>每个模块是相对独立的，其目录结构如下:<br><figure class="highlight sh"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">├─Module         模块目录</span><br><span class="line">│  ├─Conf        配置文件目录</span><br><span class="line">│  ├─Common      公共函数目录</span><br><span class="line">│  ├─Controller  控制器目录</span><br><span class="line">│  ├─Model       模型目录</span><br><span class="line">│  ├─Logic       逻辑目录（可选）</span><br><span class="line">│  ├─Service     Service目录（可选）</span><br><span class="line">│  ... 更多分层目录可选</span><br><span class="line">│  └─View        视图目录</span><br></pre></td></tr></table></figure></p>
<p>公共模块<br>Common模块是一个特殊的模块，是应用的公共模块，访问所有的模块之前都会首先加载公共模块下面的配置文件（Conf/config.php）和公共函数文件（Common/function.php）。但Common模块本身不能通过URL直接访问，公共模块的其他文件则可以被其他模块继承或者调用。<br>公共模块的位置可以通过COMMON_PATH常量改变，我们可以在入口文件中重新定义COMMON_PATH如下：<br><figure class="highlight php"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">define(<span class="string">'COMMON_PATH'</span>,<span class="string">'./Common/'</span>);</span><br><span class="line">define(<span class="string">'APP_PATH'</span>,<span class="string">'./Application/'</span>);</span><br><span class="line"><span class="keyword">require</span> <span class="string">'./ThinkPHP/ThinkPHP.php'</span>;</span><br></pre></td></tr></table></figure></p>
<p>其应用目录结构变成：<br><figure class="highlight php"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">www  WEB部署目录（或者子目录）</span><br><span class="line">├─index.php       入口文件</span><br><span class="line">├─README.md       README文件</span><br><span class="line">├─Common          应用公共模块目录</span><br><span class="line">├─Application     应用模块目录</span><br><span class="line">├─<span class="keyword">Public</span>          应用资源文件目录</span><br><span class="line">└─ThinkPHP        框架目录</span><br></pre></td></tr></table></figure></p>
<p>自动生成模块目录<br>例如，如果我们需要生成一个Admin模块用于后台应用，在应用入口文件中定义如下：<br><figure class="highlight php"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 绑定Admin模块到当前入口文件</span></span><br><span class="line">define(<span class="string">'BIND_MODULE'</span>,<span class="string">'Admin'</span>);</span><br><span class="line">define(<span class="string">'APP_PATH'</span>,<span class="string">'./Application/'</span>);</span><br><span class="line"><span class="keyword">require</span> <span class="string">'./ThinkPHP/ThinkPHP.php'</span>;</span><br></pre></td></tr></table></figure></p>
<p>然后访问URL地址<br><figure class="highlight php"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">http:<span class="comment">//serverName/index.php</span></span><br></pre></td></tr></table></figure></p>
<p>就会生成Admin模块的目录，并生成一个默认的控制器类Admin\Controller\IndexController。 如果需要生成更多的控制器类，可以定义BUILD_CONTROLLER_LIST常量，例如：<br><figure class="highlight php"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 绑定Admin模块到当前入口文件</span></span><br><span class="line">define(<span class="string">'BIND_MODULE'</span>,<span class="string">'Admin'</span>);</span><br><span class="line">define(<span class="string">'BUILD_CONTROLLER_LIST'</span>,<span class="string">'Index,User,Menu'</span>);</span><br><span class="line">define(<span class="string">'APP_PATH'</span>,<span class="string">'./Application/'</span>);</span><br><span class="line"><span class="keyword">require</span> <span class="string">'./ThinkPHP/ThinkPHP.php'</span>;</span><br></pre></td></tr></table></figure></p>
<p>访问后会自动生成三个指定的控制器类：<br><figure class="highlight php"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">Admin\Controller\IndexController</span><br><span class="line">Admin\Controller\UserController</span><br><span class="line">Admin\Controller\MenuController</span><br></pre></td></tr></table></figure></p>
<p>禁止访问模块<br><figure class="highlight php"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 设置禁止访问的模块列表</span></span><br><span class="line"><span class="string">'MODULE_DENY_LIST'</span>      =&gt;  <span class="keyword">array</span>(<span class="string">'Common'</span>,<span class="string">'Runtime'</span>,<span class="string">'Api'</span>),</span><br></pre></td></tr></table></figure></p>
<p>设置后，Api模块不能通过URL直接访问，事实上，可能我们只是在该模块下面放置一些公共的接口文件，因此都是内部调用即可。<br>如果你的应用下面模块比较少，还可以设置允许访问列表和默认模块，这样可以简化默认模块的URL访问。<br><figure class="highlight php"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="string">'MODULE_ALLOW_LIST'</span>    =&gt;    <span class="keyword">array</span>(<span class="string">'Home'</span>,<span class="string">'Admin'</span>,<span class="string">'User'</span>),</span><br><span class="line"><span class="string">'DEFAULT_MODULE'</span>       =&gt;    <span class="string">'Home'</span>,</span><br></pre></td></tr></table></figure></p>
<p>单模块设计<br>如果你的应用够简单，那么也许仅仅用一个模块就可以完成，那么可以直接设置：<br><figure class="highlight php"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 关闭多模块访问</span></span><br><span class="line"><span class="string">'MULTI_MODULE'</span>          =&gt;  <span class="keyword">false</span>,</span><br><span class="line"><span class="string">'DEFAULT_MODULE'</span>        =&gt;  <span class="string">'Home'</span>,</span><br></pre></td></tr></table></figure></p>
<p>一旦关闭多模块访问后，就只能访问默认模块（这里设置的是Home）。</p>
<p>多入口设计<br>可以给相同的应用及模块设置多个入口，不同的入口文件可以设置不同的应用模式或者绑定模块。<br><figure class="highlight php"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 绑定Home模块到当前入口文件</span></span><br><span class="line">define(<span class="string">'BIND_MODULE'</span>,<span class="string">'Home'</span>);</span><br><span class="line">define(<span class="string">'APP_PATH'</span>,<span class="string">'./Application/'</span>);</span><br><span class="line"><span class="keyword">require</span> <span class="string">'./ThinkPHP/ThinkPHP.php'</span>;</span><br></pre></td></tr></table></figure></p>
<p>URL模式<br>ThinkPHP框架的URL是区分大小写（主要是针对模块、控制器和操作名，不包括应用参数）的，这一点非常关键，因为ThinkPHP的命名规范是采用驼峰法（首字母大写）的规则，而URL中的模块和控制器都是对应的文件，因此在Linux环境下面必然存在区分大小写的问题。<br>普通模式<br>普通模式也就是传统的GET传参方式来指定当前访问的模块和操作，例如： <a href="http://localhost/?m=home&amp;c=user&amp;a=login&amp;var=value" target="_blank" rel="noopener">http://localhost/?m=home&amp;c=user&amp;a=login&amp;var=value</a><br>m参数表示模块，c参数表示控制器，a参数表示操作（当然这些参数都是可以配置的），后面的表示其他GET参数。<br>如果默认的变量设置和你的应用变量有冲突的话，你需要重新设置系统配置，例如改成下面的：<br><figure class="highlight php"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="string">'VAR_MODULE'</span>            =&gt;  <span class="string">'module'</span>,     <span class="comment">// 默认模块获取变量</span></span><br><span class="line"><span class="string">'VAR_CONTROLLER'</span>        =&gt;  <span class="string">'controller'</span>,    <span class="comment">// 默认控制器获取变量</span></span><br><span class="line"><span class="string">'VAR_ACTION'</span>            =&gt;  <span class="string">'action'</span>,    <span class="comment">// 默认操作获取变量</span></span><br></pre></td></tr></table></figure></p>
<p>上面的访问地址则变成： <a href="http://localhost/?module=home&amp;controller=user&amp;action=login&amp;var=value" target="_blank" rel="noopener">http://localhost/?module=home&amp;controller=user&amp;action=login&amp;var=value</a></p>
<p>PATHINFO模式<br>PATHINFO模式是系统的默认URL模式，提供了最好的SEO支持，系统内部已经做了环境的兼容处理，所以能够支持大多数的主机环境。对应上面的URL模式，PATHINFO模式下面的URL访问地址是： <a href="http://localhost/index.php/home/user/login/var/value/" target="_blank" rel="noopener">http://localhost/index.php/home/user/login/var/value/</a><br>PATHINFO模式下面，URL是可定制的，例如，通过下面的配置：<br><figure class="highlight php"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 更改PATHINFO参数分隔符</span></span><br><span class="line"><span class="string">'URL_PATHINFO_DEPR'</span>=&gt;<span class="string">'-'</span>,</span><br></pre></td></tr></table></figure></p>
<p>REWRITE模式<br>REWRITE模式是在PATHINFO模式的基础上添加了重写规则的支持，可以去掉URL地址里面的入口文件index.php，但是需要额外配置WEB服务器的重写规则。<br>如果是Apache则需要在入口文件的同级添加.htaccess文件，内容如下：<br><figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">IfModule</span> <span class="attr">mod_rewrite.c</span>&gt;</span></span><br><span class="line"> RewriteEngine on</span><br><span class="line"> RewriteCond %&#123;REQUEST_FILENAME&#125; !-d</span><br><span class="line"> RewriteCond %&#123;REQUEST_FILENAME&#125; !-f</span><br><span class="line"> RewriteRule ^(.*)$ index.php/$1 [QSA,PT,L]</span><br><span class="line"><span class="tag">&lt;/<span class="name">IfModule</span>&gt;</span></span><br></pre></td></tr></table></figure></p>
<p>接下来，就可以用下面的URL地址访问了： <a href="http://localhost/home/user/login/var/value" target="_blank" rel="noopener">http://localhost/home/user/login/var/value</a></p>
<p>兼容模式<br>可以更改兼容模式变量的名称定义，例如：<br><figure class="highlight php"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="string">'VAR_PATHINFO'</span>          =&gt;  <span class="string">'path'</span></span><br></pre></td></tr></table></figure></p>
<p>PATHINFO参数分隔符对兼容模式依然有效，例如：<br><figure class="highlight php"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 更改PATHINFO参数分隔符</span></span><br><span class="line"><span class="string">'URL_PATHINFO_DEPR'</span>=&gt;<span class="string">'-'</span>,</span><br></pre></td></tr></table></figure></p>
<p>使用以上配置的话，URL访问地址可以变成： <a href="http://localhost/?path=/home-user-login-var-value" target="_blank" rel="noopener">http://localhost/?path=/home-user-login-var-value</a><br>兼容模式配合Web服务器重写规则的定义，可以达到和REWRITE模式一样的URL效果。<br>例如，我们在Apache下面的话，.htaccess文件改成如下内容：<br><figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">IfModule</span> <span class="attr">mod_rewrite.c</span>&gt;</span></span><br><span class="line"> RewriteEngine on</span><br><span class="line"> RewriteCond %&#123;REQUEST_FILENAME&#125; !-d</span><br><span class="line"> RewriteCond %&#123;REQUEST_FILENAME&#125; !-f</span><br><span class="line"> RewriteRule ^(.*)$ index.php?s=/$1 [QSA,PT,L]</span><br><span class="line"><span class="tag">&lt;/<span class="name">IfModule</span>&gt;</span></span><br></pre></td></tr></table></figure></p>
<p>就可以和REWRITE模式一样访问下面的URL地址访问了： <a href="http://localhost/home/user/login/var/value" target="_blank" rel="noopener">http://localhost/home/user/login/var/value</a><br>………<br><a href="http://document.thinkphp.cn/manual_3_2.html" target="_blank" rel="noopener">http://document.thinkphp.cn/manual_3_2.html</a></p>

      
    </div>

    <div>
      
        

      
    </div>

    <div>
      
        

      
    </div>


    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/学习/" rel="tag"># 学习</a>
          
        </div>
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2017/07/22/first/" rel="next" title="MySQL知识点巩固">
                <i class="fa fa-chevron-left"></i> MySQL知识点巩固
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2017/07/27/first/" rel="prev" title="SVG用法">
                SVG用法 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
        <!-- JiaThis Button BEGIN -->
<div class="jiathis_style">
  <a class="jiathis_button_tsina"></a>
  <a class="jiathis_button_tqq"></a>
  <a class="jiathis_button_weixin"></a>
  <a class="jiathis_button_cqq"></a>
  <a class="jiathis_button_douban"></a>
  <a class="jiathis_button_renren"></a>
  <a class="jiathis_button_qzone"></a>
  <a class="jiathis_button_kaixin001"></a>
  <a class="jiathis_button_copy"></a>
  <a href="http://www.jiathis.com/share" class="jiathis jiathis_txt jiathis_separator jtico jtico_jiathis" target="_blank"></a>
  <a class="jiathis_counter_style"></a>
</div>
<script type="text/javascript">
  var jiathis_config={
    hideMore:false
  }
</script>
<script type="text/javascript" src="http://v3.jiathis.com/code/jia.js" charset="utf-8"></script>
<!-- JiaThis Button END -->

      
    </div>
  </div>


          </div>
          

  <p>热评文章</p>
  <div class="ds-top-threads" data-range="weekly" data-num-items="4"></div>


          
  <div class="comments" id="comments">
    
      <div id="hypercomments_widget"></div>
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope="" itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image" src="/uploads/avatar.jpg" alt="腊月的季节">
          <p class="site-author-name" itemprop="name">腊月的季节</p>
          <p class="site-description motion-element" itemprop="description">腊月的季节的个人博客</p>
        </div>
        <nav class="site-state motion-element">
          <div class="site-state-item site-state-posts">
            <a href="/archives">
              <span class="site-state-item-count">160</span>
              <span class="site-state-item-name">日志</span>
            </a>
          </div>

          
            <div class="site-state-item site-state-categories">
              <a href="/categories">
                <span class="site-state-item-count">72</span>
                <span class="site-state-item-name">分类</span>
              </a>
            </div>
          

          
            <div class="site-state-item site-state-tags">
              <a href="/tags">
                <span class="site-state-item-count">13</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        

        <div class="links-of-author motion-element">
          
        </div>

        
        

        
        
          <div class="links-of-blogroll motion-element links-of-blogroll-inline">
            <div class="links-of-blogroll-title">
              <i class="fa  fa-fw fa-globe"></i>
              我的其他足迹
            </div>
            <ul class="links-of-blogroll-list">
              
                <li class="links-of-blogroll-item">
                  <a href="http://blog.csdn.net/qq_33433029" title="CSDN博客" target="_blank">CSDN博客</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="http://github.com/youandme66" title="GitHub" target="_blank">GitHub</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="http://www.jianshu.com/users/767025e0c4df/timeline" title="我的简书" target="_blank">我的简书</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="https://www.zhihu.com/people/liu-zhi-hao-85-39/activities" title="我的知乎" target="_blank">我的知乎</a>
                </li>
              
            </ul>
          </div>
        

        


      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#命名规范"><span class="nav-number">1.</span> <span class="nav-text">命名规范</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#配置"><span class="nav-number">2.</span> <span class="nav-text">配置</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#架构"><span class="nav-number">3.</span> <span class="nav-text">架构</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">
  
  &copy;  2016 - 
  <span itemprop="copyrightYear">2019</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">腊月的季节</span>
</div>


<div class="powered-by">
   <a class="theme-link" href="http://www.jianshu.com/users/767025e0c4df/timeline">我的简书</a> 
</div>

<div class="theme-info">
  链接 -
  <a class="theme-link" href="https://www.zhihu.com/people/liu-zhi-hao-85-39/activities">
    我的知乎
  </a>
</div>


        

        
      </div>
    </footer>

    <div class="back-to-top">
      <i class="fa fa-arrow-up"></i>
    </div>
  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  



  
  <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.0"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.0"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.0"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.0"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.0"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.0"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.0"></script>


  



  




	

		<script type="text/javascript">
		_hcwp = window._hcwp || [];

		_hcwp.push({widget:"Bloggerstream", widget_id: 93245, selector:".hc-comment-count", label: "{\%COUNT%\}" });

		
		_hcwp.push({widget:"Stream", widget_id: 93245, xid: "2017/07/26/first/"});
		

		(function() {
		if("HC_LOAD_INIT" in window)return;
		HC_LOAD_INIT = true;
		var lang = (navigator.language || navigator.systemLanguage || navigator.userLanguage || "en").substr(0, 2).toLowerCase();
		var hcc = document.createElement("script"); hcc.type = "text/javascript"; hcc.async = true;
		hcc.src = ("https:" == document.location.protocol ? "https" : "http")+"://w.hypercomments.com/widget/hc/93245/"+lang+"/widget.js";
		var s = document.getElementsByTagName("script")[0];
		s.parentNode.insertBefore(hcc, s.nextSibling);
		})();
		</script>

	





  
  
  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length == 0) {
      search_path = "search.xml";
    }
    var path = "/" + search_path;
    // monitor main search box;

    function proceedsearch() {
      $("body").append('<div class="popoverlay">').css('overflow', 'hidden');
      $('.popup').toggle();
    }
    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';
      $.ajax({
        url: path,
        dataType: "xml",
        async: true,
        success: function( xmlResponse ) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = $( "entry", xmlResponse ).map(function() {
            return {
              title: $( "title", this ).text(),
              content: $("content",this).text(),
              url: $( "url" , this).text()
            };
          }).get();
          var $input = document.getElementById(search_id);
          var $resultContent = document.getElementById(content_id);
          $input.addEventListener('input', function(){
            var matchcounts = 0;
            var str='<ul class=\"search-result-list\">';
            var keywords = this.value.trim().toLowerCase().split(/[\s\-]+/);
            $resultContent.innerHTML = "";
            if (this.value.trim().length > 1) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var content_index = [];
                var data_title = data.title.trim().toLowerCase();
                var data_content = data.content.trim().replace(/<[^>]+>/g,"").toLowerCase();
                var data_url = decodeURIComponent(data.url);
                var index_title = -1;
                var index_content = -1;
                var first_occur = -1;
                // only match artiles with not empty titles and contents
                if(data_title != '') {
                  keywords.forEach(function(keyword, i) {
                    index_title = data_title.indexOf(keyword);
                    index_content = data_content.indexOf(keyword);
                    if( index_title >= 0 || index_content >= 0 ){
                      isMatch = true;
                      if (i == 0) {
                        first_occur = index_content;
                      }
                    }

                  });
                }
                // show search results
                if (isMatch) {
                  matchcounts += 1;
                  str += "<li><a href='"+ data_url +"' class='search-result-title'>"+ data_title +"</a>";
                  var content = data.content.trim().replace(/<[^>]+>/g,"");
                  if (first_occur >= 0) {
                    // cut out 100 characters
                    var start = first_occur - 20;
                    var end = first_occur + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if(start == 0){
                      end = 50;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    var match_content = content.substring(start, end);
                    // highlight all keywords
                    keywords.forEach(function(keyword){
                      var regS = new RegExp(keyword, "gi");
                      match_content = match_content.replace(regS, "<b class=\"search-keyword\">"+keyword+"</b>");
                    });

                    str += "<p class=\"search-result\">" + match_content +"...</p>"
                  }
                  str += "</li>";
                }
              })};
            str += "</ul>";
            if (matchcounts == 0) { str = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>' }
            if (keywords == "") { str = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>' }
            $resultContent.innerHTML = str;
          });
          proceedsearch();
        }
      });}

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched == false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(function(e){
      $('.popup').hide();
      $(".popoverlay").remove();
      $('body').css('overflow', '');
    });
    $('.popup').click(function(e){
      e.stopPropagation();
    });
  </script>


  
  
    <script type="text/x-mathjax-config">
      MathJax.Hub.Config({
        tex2jax: {
          inlineMath: [ ['$','$'], ["\\(","\\)"]  ],
          processEscapes: true,
          skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
        }
      });
    </script>

    <script type="text/x-mathjax-config">
      MathJax.Hub.Queue(function() {
        var all = MathJax.Hub.getAllJax(), i;
        for (i=0; i < all.length; i += 1) {
          all[i].SourceElement().parentNode.className += ' has-jax';
        }
      });
    </script>
    <script type="text/javascript" src="//cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
  


  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.1.js"></script>
  <script>AV.initialize("EAvSG3QtXW1dqzq5WQ5CjH7S-gzGzoHsz", "2aiWv7vIfVY4CjKc49aPBHFX");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  
<script>
(function(){
    var bp = document.createElement('script');
    var curProtocol = window.location.protocol.split(':')[0];
    if (curProtocol === 'https') {
        bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';        
    }
    else {
        bp.src = 'http://push.zhanzhang.baidu.com/push.js';
    }
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(bp, s);
})();
</script>


  

</body>
</html>
